package com.mofum.scope.controller;

import com.mofum.scope.common.IScopeAuthenticator;
import com.mofum.scope.common.IScopeConverter;
import com.mofum.scope.common.IScopeExtractor;
import com.mofum.scope.common.model.Scope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author developer@omuao.com
 * @since 2019-03-28
 **/
public class ScopeController implements IScopeExtractor<Object, RuntimeException>, IScopeAuthenticator<List<Scope>, RuntimeException>, IScopeConverter<Object, RuntimeException> {

    @Override
    public List<Scope> convert2Scope(Object o) throws RuntimeException {
        //转换业务对象为ScopeId
        List<Scope> scopes = new ArrayList<>();
        Scope scope = new Scope();
        scope.setId("1");
        scope.setType("ScopeOne"); //Type和IUserService 中的注解ColumnScope要指定同一个注解才能生效
        scopes.add(scope);
        return scopes;
    }

    @Override
    public boolean testAccess(List<Scope> scopes) throws RuntimeException {

        //取用户ID
        String userId = getRequest().getParameter("userId");

        //取请求URL

        String url = getRequest().getRequestURI();


        System.out.println(scopes);

        boolean accessFlag = false;
        //验证权限逻辑
        for (Scope scope : scopes) {

            if (scope.getId().equals("2")) {
                return true;
            }

        }

        if (!accessFlag) {
            throw new RuntimeException("Operation failed!Cause no permission!(action :" + url + ")");
        }

        return accessFlag;
    }

    @Override
    public List<? extends Scope> extractorScopes(Object o) throws RuntimeException {

        //提取权限数据范围

        //假设只有SCOPE_ONE只有权限范围1

        List<Scope> scopes = new ArrayList<>();
        Scope scope = new Scope();
        scope.setId("1");
        scope.setType("ScopeOne"); //Type和IUserService 中的注解ColumnScope要指定同一个注解才能生效
        scopes.add(scope);

        return scopes;
    }

    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

}
